#!/bin/sh
# scripts daemon, add to /etc/crontab
# */1 *   *   *   *   root    PATH/script.sh --daemon

# run on root
if [ "$(uname -s|grep -F 'CYGWIN')" = "" ] && [ $UID -ne 0 ]; then
    echo "superuser privileges are required to run this script."
    exit 1
fi

# settings
PHP_CLI="/usr/local/php/bin/php -c /usr/local/php/etc/php.ini"
SCRIPTS=" PaijuLogHandler PayLogHandler DiamondLogHandler.php PaijuTableHandler PaijuExtTableHandler PaijuClubActivityTopHandler LogTableHandler"

# paths
BASE_PATH=$(cd $(dirname $0) && pwd)
BASE_SCRIPT="$BASE_PATH/script.php"
LOGS_PATH="$BASE_PATH/data/logs/bash.log"

USAGE="Usage: $(basename $0) [-d|-a|-k SCRIPT]\n\
  -d, --daemon\t\tthe daemon mode, runing checking\n\
  -a, --killall\t\tkill the all scripts\n\
  -k, --kill SCRIPT\tkill the SCRIPT\n\
  -h, --help\t\tthis help text"

function get_pid()
{
	echo $(ps -ef|grep -F "$1"|grep -v "grep"|awk '{print $2}')
}

function kill_script()
{
	PID=$(get_pid "$1")
	if [ "$PID" = "" ]; then
		echo "$1 not found"
	else
		kill -9 $PID
		echo "$1 has been killed, pid: $PID"
	fi
}

case $1 in
	-k|--kill)
		if [ "$2" = "" ]; then
			echo -e $USAGE
			exit 0
		fi
		kill_script "$BASE_SCRIPT request/$2"
		;;
	-a|--killall)
		for SCRIPT in $SCRIPTS; do
			kill_script "$BASE_SCRIPT request/$SCRIPT"
		done
		;;
	-d|--daemon)
		for SCRIPT in $SCRIPTS; do
			SCRIPT="$BASE_SCRIPT request/$SCRIPT"
			PID=$(get_pid "$SCRIPT")
			if [ "$PID" = "" ]; then
				eval "$PHP_CLI $SCRIPT >/dev/null 2>&1 &"
				PID=$(get_pid "$SCRIPT")
				echo "[$(date +%Y-%m-%d\ %H:%M:%S)] $SCRIPT has been down, restarted: $PID" >> $LOGS_PATH
			fi
		done
		;;
	*)
		echo -e $USAGE
		;;
esac
